'use strict';

var express = require('express');
var router = express.Router();
var jstat = require('../cmd').jstat;


var Error_Data = {
  heap:{
    total: -1,
    used: -1,
    percent: -1
  },
  gc:{
    young:{
      count: -1,
      time: -1
    },
    full:{
      count: -1,
      time: -1
    }
  }
};


router.get('/jstat/:port.:format', function(req, res) {
  var port = parseInt(req.params.port);
  var format = req.params.format || 'html';

  var callback = (format == 'jsonp') && (req.query.callback || '_callback')
  var status = jstat(port);

  if(!!status.error){
    var data = {
      data: Error_Data
    };
    if(!!callback){
      data.callback = callback;
    }
    res.render('jstat-'+format, data);
  }else{
    var data = {
      heap:{},
      gc:{
        young:{},
        full:{}
      }
    };

    if('hotspot' == status.java.vendor){

      // perm renamed meta over jdk8 
      // PC -> MC ,PO -> MO
      var perm_key = status.java.version <=7?'P':'M';
      
      data.heap.total = (Number(status.data['S1C']) 
        + Number(status.data['S0C'])
        + Number(status.data['EC'])
        + Number(status.data['OC'])
        + Number(status.data[perm_key+'C'])).toFixed(2);
      data.heap.used = (Number(status.data['S1U']) 
        + Number(status.data['S0U'])
        + Number(status.data['EU'])
        + Number(status.data['OU'])
        + Number(status.data[perm_key+'U'])).toFixed(2);
      data.heap.percent = Number(data.heap.used * 100 / data.heap.total).toFixed(2);

      data.gc.young.count = parseInt(status.data['YGC']);
      data.gc.young.time = Number(status.data['YGCT']).toFixed(3);

      data.gc.full.count = parseInt(status.data['FGC']);
      data.gc.full.time = Number(status.data['FGCT']).toFixed(3);

    }else if('jrockit' == status.java.vendor){
      if(status.java.version >6){
        throw Error('not supported JVM over jrokit 6');
      }else{
        data.heap.total = Number(status.data['HeapSize']).toFixed(2);
        data.heap.used = Number(status.data['UsedHeapSize']).toFixed(2);
        data.heap.percent = Number(data.heap.used * 100 / data.heap.total).toFixed(2);

        data.gc.young.count = Number(status.data['YC']);
        data.gc.young.time = Number(status.data['YCTime']).toFixed(3);

        data.gc.full.count = Number(status.data['OC']);
        data.gc.full.time = Number(status.data['OCTime']).toFixed(3);
      }
    }

    var renderData = {
      data: data
    };

    if(!!callback){
      renderData.callback = callback;
    }    

    res.render('jstat-'+format, renderData);
  }


  
  
});

module.exports = router;

